package com.wtwd.campus.attendancenetty;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.utils.InjectService;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

@Component
public class AttendanceChannelHandler {

	public static void addOrRefreshChannel(String productNo, Channel channel) {
		Channel $channel = AttendanceChannelMap.get(Constants.ATTENDANCE_ONLINE_PRE.concat(productNo));
		if($channel == null){
			AttendanceChannelMap.add(Constants.ATTENDANCE_ONLINE_PRE.concat(productNo),channel);
		}else{
			if(!$channel.equals(channel)){  // 如果通道已改变
				AttendanceChannelMap.removeByKey(Constants.ATTENDANCE_ONLINE_PRE.concat(productNo));
				AttendanceChannelMap.add(Constants.ATTENDANCE_ONLINE_PRE.concat(productNo),channel);
			}
		}
		//设置考勤机的在线状态
		InjectService.setAttendanceDeviceOnline(Constants.ATTENDANCE_ONLINE_PRE.concat(productNo));
	}

	public static Channel getChannel(String productNo) {
		return AttendanceChannelMap.get(Constants.ATTENDANCE_ONLINE_PRE.concat(productNo));
	}


	public static void closeChannel(Channel channel) {
		String key = AttendanceChannelMap.getKey(channel);
		AttendanceChannelMap.removeByKey(key);
		channel.close();
		//关闭通道后需要删除redis中存储的在线状态
		InjectService.removeOnline(key);
	}

}
